package my.web;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
@ComponentScan({"controller","com.**.controller","**.ctl","org.xdq.**.controller","org.xdq.**.service","org.xdq.**.dao"})
@EnableWebMvc
public class RootConfig extends WebMvcConfigurerAdapter {
	
	private static final Log LOG = LogFactory.getLog(RootConfig.class);

	
	
	//放行静态资源
	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
		LOG.info("配置默认Servlet，以确保正常访问静态资源。");
	}

	//设置首页
	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/").setViewName("redirect:/index.html");
		LOG.info("配置默认首页地址为 /index.html 。");
	}

	//跨域设置
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**") //允许所有请求路径跨域
				.allowedOrigins("*")
				.allowedHeaders("*")
				.allowCredentials(true) //允许客户端发送session认证信息
				.allowedMethods("*"); //允许所有请求方法跨域
		LOG.info("跨域配置：允许所有请求路径跨域、允许客户端发送session认证信息、允许所有请求方法跨域、允许任意header跨域、允许任意origins跨域 。");
	}

	//配置fastjson为请求和相应信息的json转换器
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		
		StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
		
		
		
		stringConverter.setDefaultCharset(Charset.forName("UTF-8"));
		
		List<MediaType> stringMediaTypeList = new ArrayList<MediaType>();
		stringMediaTypeList.add(MediaType.TEXT_PLAIN);
		stringMediaTypeList.add(MediaType.TEXT_HTML);
		stringMediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
		stringConverter.setSupportedMediaTypes(stringMediaTypeList);
		
		converters.add(0, stringConverter);
		
		

		FastJsonHttpMessageConverter jsonConverter = new FastJsonHttpMessageConverter();
		
		jsonConverter.setDefaultCharset(Charset.forName("UTF-8"));
		
		List<MediaType> jsonMediaTypeList = new ArrayList<MediaType>();
		jsonMediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
		jsonConverter.setSupportedMediaTypes(jsonMediaTypeList);
		
		converters.add(1, jsonConverter);
		
		

		LOG.info("配置json转换器使用阿里巴巴的Fastjson。");
	}
	
	//配置拦截器
	@Override
    public void addInterceptors(InterceptorRegistry registry) {       
        registry.addInterceptor(nocacheInterceptor()).addPathPatterns("/**");
        LOG.info("配置请求编码为UTF-8；配置禁用浏览器缓存。");
    }

	//禁用浏览器缓存拦截器
	public HandlerInterceptor nocacheInterceptor() {

		return new HandlerInterceptor() {

			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
					throws Exception {

				request.setCharacterEncoding("UTF-8");
				
				response.addHeader("Pragma", "no-cache");
				response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
				response.addHeader("Cache-Control", "pre-check=0, post-check=0");
				response.setDateHeader("Expires", 0);

				return true;

			}

			@Override
			public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
					throws Exception {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
					throws Exception {
				// TODO Auto-generated method stub
				
			}
		};

	}

}
